# 超时
import heapq
# class Solution(object):
#     def maxEvents(self, events):
#         heapq.heapify(events)
#         time = 0
#         ans = 0
#         while events:
#             node = heapq.heappop(events)
#             if node[0] > time:
#                 time = node[0]
#                 ans += 1
#             else:
#                 if node[1] > time:
#                     heapq.heappush(events, [time + 1, node[1]])
#         return ans

import sortedcontainers
class Solution(object):
    def maxEvents(self, events):
        events.sort()
        time = 1
        index = 0
        n = len(events)
        st = sortedcontainers.SortedList()
        ans = 0
        for time in range(10 ** 5 + 1):
            while index < n and time == events[index][0]:
                st.add(events[index][1])
                index += 1
            if st:
                node = st.pop(0)
                while st and node < time:
                    node = st.pop(0)
                if node >= time:
                    ans += 1
        return ans



data = Solution()
events = [[1, 2], [1, 2], [1, 6], [1, 2], [1, 2]]
print(data.maxEvents(events))
events = [[1, 10], [2, 2], [2, 2], [2, 2], [2, 2]]
print(data.maxEvents(events))
